<template>
  <div class="voice-demo-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>语音录入功能演示</span>
        </div>
      </template>
      
      <div class="demo-section">
        <h3>功能说明</h3>
        <ul>
          <li>点击字段旁边的麦克风图标开始语音录入</li>
          <li>支持中文语音识别，实时转换为文字</li>
          <li>可以为不同字段分别录入语音</li>
          <li>录音时图标会变红并有动画效果</li>
          <li>再次点击或点击其他字段麦克风停止当前录音</li>
        </ul>
      </div>

      <div class="demo-section">
        <h3>浏览器兼容性</h3>
        <div class="compatibility-info">
          <span :class="['status', isSupported ? 'supported' : 'not-supported']">
            {{ isSupported ? '✓ 支持语音识别' : '✗ 不支持语音识别' }}
          </span>
          <p v-if="!isSupported" class="tip">
            请使用 Chrome、Edge 或 Safari 浏览器体验语音功能
          </p>
        </div>
      </div>

      <div class="demo-section">
        <h3>当前状态</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-tag :type="isListening ? 'danger' : 'info'">
              {{ isListening ? '正在录音' : '未录音' }}
            </el-tag>
          </el-col>
          <el-col :span="8" v-if="currentField">
            <el-tag type="warning">
              当前字段: {{ getCurrentFieldLabel() }}
            </el-tag>
          </el-col>
          <el-col :span="8" v-if="error">
            <el-tag type="danger">
              {{ error }}
            </el-tag>
          </el-col>
        </el-row>
      </div>

      <div class="demo-section">
        <h3>医疗记录表单</h3>
        <medical-record-fields 
          v-model="formData"
          @voice-start="onVoiceStart"
          @voice-end="onVoiceEnd"
          @voice-error="onVoiceError"
          ref="medicalFormRef"
        />
      </div>

      <div class="demo-section">
        <h3>表单数据</h3>
        <el-button @click="validateForm" type="primary">验证表单</el-button>
        <el-button @click="clearForm" type="danger">清空表单</el-button>
        <el-button @click="exportData" type="success">导出数据</el-button>
        
        <el-collapse v-model="activeCollapse" class="data-preview">
          <el-collapse-item title="查看表单数据" name="data">
            <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useSpeechRecognition } from '~/composables/useSpeechRecognition'


// 表单数据
const formData = ref<Record<string, string>>({})

// 折叠面板状态
const activeCollapse = ref([''])

// 医疗表单引用
const medicalFormRef = ref()

// 语音识别状态
const speechRecognition = useSpeechRecognition()

// 计算属性
const isSupported = computed(() => speechRecognition.isSupported.value)
const isListening = computed(() => speechRecognition.isListening.value)
const error = computed(() => speechRecognition.error.value)
const currentField = computed(() => medicalFormRef.value?.currentField || '')

// 字段标签映射
const fieldLabels: Record<string, string> = {
  chiefComplaint: '主诉',
  presentIllness: '现病史',
  pastHistory: '既往史',
  personalHistory: '个人史',
  familyHistory: '家族史',
  physicalExam: '体格检查',
  auxiliaryExam: '辅助检查',
  diagnosis: '诊断',
  treatment: '治疗方案',
  notes: '备注'
}

// 获取当前字段标签
const getCurrentFieldLabel = () => {
  return fieldLabels[currentField.value] || currentField.value
}

// 语音事件处理
const onVoiceStart = (fieldKey: string) => {
  //console.log('语音开始:', fieldKey)
  ElNotification({
    title: '语音录入',
    message: `开始录入 ${fieldLabels[fieldKey]}`,
    type: 'info',
    duration: 2000
  })
}

const onVoiceEnd = (fieldKey: string, transcript: string) => {
  //console.log('语音结束:', fieldKey, transcript)
  ElNotification({
    title: '录入完成',
    message: `${fieldLabels[fieldKey]} 录入完成`,
    type: 'success',
    duration: 2000
  })
}

const onVoiceError = (fieldKey: string, error: string) => {
  //console.error('语音错误:', fieldKey, error)
  ElNotification({
    title: '录入错误',
    message: `${fieldLabels[fieldKey]}: ${error}`,
    type: 'error',
    duration: 3000
  })
}

// 表单操作
const validateForm = () => {
  if (medicalFormRef.value) {
    const result = medicalFormRef.value.validate()
    if (result.valid) {
      ElMessage.success('表单验证通过')
    } else {
      //ElMessage.error('表单验证失败')
      //console.log('验证错误:', result.errors)
    }
  }
}

const clearForm = () => {
  if (medicalFormRef.value) {
    medicalFormRef.value.clearAll()
    formData.value = {}
    ElMessage.success('表单已清空')
  }
}

const exportData = () => {
  const dataStr = JSON.stringify(formData.value, null, 2)
  const blob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `medical-record-${Date.now()}.json`
  link.click()
  URL.revokeObjectURL(url)
  ElMessage.success('数据已导出')
}
</script>

<style scoped>
.voice-demo-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.demo-section {
  margin-bottom: 30px;
  
  h3 {
    margin-bottom: 15px;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
  
  ul {
    padding-left: 20px;
    line-height: 1.8;
    color: #606266;
  }
}

.compatibility-info {
  .status {
    padding: 8px 16px;
    border-radius: 4px;
    font-weight: 500;
    
    &.supported {
      background-color: #f0f9ff;
      color: #059669;
      border: 1px solid #a7f3d0;
    }
    
    &.not-supported {
      background-color: #fef2f2;
      color: #dc2626;
      border: 1px solid #fca5a5;
    }
  }
  
  .tip {
    margin-top: 10px;
    color: #909399;
    font-size: 14px;
  }
}

.data-preview {
  margin-top: 20px;
  
  pre {
    background-color: #f5f7fa;
    padding: 15px;
    border-radius: 6px;
    font-size: 12px;
    line-height: 1.4;
    max-height: 300px;
    overflow-y: auto;
  }
}

:deep(.el-button) {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
